/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/variable.ts" />
/// <reference path="../utils/js.ts" />
/// <reference path="../log/log-manager.ts" />

namespace lcc {

const Path = require('path');
const FS = require('fs');

const TAG = "lcc/config/config-manager.ts";

/**
 * @zh
 * 下载远程配置超时时间
 */
export let REMOTE_CONFIG_TIMEOUT = 5;

/**
 * @zh
 * 配置文件的默认路径
 */
export let CONFIG_PATH = Path.join(__dirname, 'config');

/**
 * @zh
 * 配置对象映射表<br/>
 * 在加载完对应配置后，可以直接通过这个变量访问配置数据<br/>
 * ```
 *      lcc.configMgr.loadConfig('test');
 *      let testConfig = CONFIGS.test;
 *      // let testConfig = CONFIGS['test'];
 * ```
 */
export let CONFIGS:{[key:string]:any} = js.createMap();

/**
 * @zh
 * 加载配置选项<br/>
 * 在加载配置的时候，可以有更多配置选择<br/>
 * ```
 *      lcc.configMgr.loadConfig('test', { configName : 'newName' });
 * ```
 */
export interface LoadConfigOption {
    /**
     * @zh
     * 配置名称<br/>
     * 可以修改配置加载后的名称<br/>
     * 如果没有指定，则会使用配置文件的名作为配置名  
     */
    configName?:string;

    /**
     * @zh
     * 合并当前配置<br/>
     * 如果`CONFIGS`中存在当前名称的配置，那么会把当前配置合并到原有配置上<br/>
     * 否则，当前配置会替换原有存在配置
     */
    merge?:boolean;
}

/**
 * @zh
 * 配置管理器<br/>
 * 主要用于管理程序的配置与远程配置<br/>
 * 可以对本地配置表中的变量进行替换，并且可以合并配置  
 */
class ConfigManager {
	
    /**
     * @zh
     * 获得所有配置<br/>
     * 也可以直接使用`CONFIGS`
     */
    public getConfigs(){
        return CONFIGS;
    }
    
    /**
     * @zh
     * 获得对应配置<br/>
     * 也可以直接使用`CONFIGS[key]`
     */
    public getConfig<T = any>(key:string){
        return CONFIGS[key] as T;
    }
	
	/**
     * @zh
	 * 移除所有配置
	 */
	public removeAllConfigs(){
		for(let cname of Object.keys(CONFIGS)){
			delete CONFIGS[cname];
		}
    }
    
    /**
     * @zh
     * 移除指定配置<br/>
     * 
     * @param cname - 配置名称
     */
	public removeConfig(cname:string){
		delete CONFIGS[cname];
	}
	
    /**
     * @zh
     * 解析配置对象</br>
     * 1、解析配置中的引用</br>
     *      "@key1":"http://localhost/config.json"     =>   "key1" : [具体内容]</br>
     *      "@key2":"C://config1.json"                 =>   "key2" : [具体内容]</br>
     * 
     * @param config 配置对象
     */
    private async parseConfigObject(config:any){
        for(let k of Object.keys(config)){
            let v = config[k];
            let vtp = typeof(v);
            if (vtp == 'object'){
                await this.parseConfigObject(v);
            }else if(vtp == 'string' && k.indexOf('@') == 0){
                let nc =  await this.readConfigFile(v);
                if(nc){
                    config[k.substr(1)] = nc;
                    delete config[k];
                }else{
                    logMgr.error(TAG, `parseConfig file '${v}' not found!!!`);
                }
            }
        }
    }

    /**
     * @zh
     * 读取配置文件
     * 
     * @param pathOrUrl 路径或者URL
     */
    private async readConfigFile(pathOrUrl:string){
        let content:string = null;
        if(pathOrUrl.indexOf('http://') == 0 || pathOrUrl.indexOf('https://') == 0){
            content = await http.get(pathOrUrl, REMOTE_CONFIG_TIMEOUT);
        }else{
            content = FS.readFileSync(pathOrUrl, { encoding : 'utf8' });
        }
        if(content){
            content = parseVariables(content, { localpath : Path.dirname(pathOrUrl).replace(/\\/g, '/') });
            let config = JSON.parse(content);
            await this.parseConfigObject(config);
            return config;
        }
    }

	/**
     * @zh
	 * 加载配置文件<br/>
     * 具体功能和 [[ConfigManager.loadConfig]] 一样<br/>
     * 用法：<br/>
     * 如果有个配置文件路径是 `C://test/version.json`<br/>
     * ```
     *      // 加载配置为 version
     *      lcc.configMgr.loadConfigFile('C://test/version.json');
     *      
     *      // 加载配置为 test，并且test存在直接合并
     *      lcc.configMgr.loadConfigFile('C://test/version.json', {configName : 'test', merge : true});
     * ```
     * 
	 * @param jfile - 配置文件的全路径，当前仅支持JSON 
     * @param nameOrOption - 自定义配置名称或者选项
	 */
     public async loadConfigFile(jfile:string, nameOrOption?:string|LoadConfigOption){
        let localconf = await this.readConfigFile(jfile);
        if(localconf){
            let option:LoadConfigOption;
            if(typeof nameOrOption == 'string'){
                option = {
                    configName : nameOrOption,
                };
            }else{
                option = nameOrOption || {};
            }
            option.configName = option.configName || Path.basename(jfile, '.json');
            DEBUG.CONFIG && logMgr.debug(TAG, `local config ${option.configName} : ${JSON.stringify(localconf)}`);
            if(!option.merge){
                delete CONFIGS[option.configName];
            }
            let config = CONFIGS[option.configName];
            if(!config){
                config = js.createMap();
                CONFIGS[option.configName] = config;
            }
            js.mergeMap(config, localconf, { tag : TAG, source : jfile });
        }else{
            logMgr.error(TAG, `loadConfigFile '${jfile}' not found!!!`);
        }
	}
	
    /**
     * @zh
     * 根据默认路径加载配置<br/>
     * 默认加载路径为[[CONFIG_PATH]]</br>
     * 用法：<br/>
     * 如果有配置文件路径是 `C://test/version.json`<br/>
     * ```
     *      // 设置配置默认路径，这个设置应该在程序最开始的地方统一配置
     *      lcc.CONFIG_PATH = 'C://test';
     * 
     *      ...
     *
     *      // 直接使用文件名加载，注意不含后缀json
     *      lcc.configMgr.loadConfig('version');
     *      // 使用 option，加载后的配置名为`test`, 如果`test`已经存在，直接替换
     *      lcc.configMgr.loadConfig('version',{ configName : 'test' });
     * ```
     * 
     * @param config - 加载的配置，注意不要后缀
    * @param nameOrOption - 自定义配置名称或者选项
     */
    public async loadConfig(config:string, nameOrOption?:string|LoadConfigOption){
        await this.loadConfigFile(Path.join(CONFIG_PATH, `${config}.json`), nameOrOption);
    }

};

/**
 * @zh
 * 配置管理器单例对象
 */
export const configMgr = new ConfigManager();

}
